<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-form :form="form">

      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>

      <a-form-item
        label="回收单号"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          v-decorator="['pickNo', {rules: [{required: false, message: '回收单号不能为空'}]}]" />
      </a-form-item>
      <a-form-item
        label="回收类型"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select v-decorator="['type', {initialValue:DictCache.VALUE.SPARE_RECOVERY_FORM_TYPE.EXPIRED,rules: [{required: true, message: '回收类型不能为空'}]}]" placeholder="请选择">
          <a-select-option
            v-for="(label,value) in typeMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>
       <a-form-item
          label="回收人"
          :labelCol="BaseTool.Constant.labelCol"
          :wrapperCol="BaseTool.Constant.wrapperCol"
        >
          <a-select v-decorator="['pickUserId', {rules: [{required: true, message: '回收人不能为空'}]}]" placeholder="请选择">
            <a-select-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.realName"
              :value="item.userId">{{ item.realName }}
            </a-select-option>
          </a-select>
        </a-form-item>

      <a-form-item
        label="回收说明"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          v-decorator="['reason', {rules: [{required: true, message: '回收说明不能为空'}]}]" />
      </a-form-item>
      <a-form-item
        label="状态"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select v-decorator="['status', {initialValue:DictCache.VALUE.SPARE_RECOVERY_FORM_STATUS.APPROVAL_PENDING,rules: [{required: true, message: '状态不能为空'}]}]" placeholder="请选择">
          <a-select-option
            v-for="(label,value) in statusMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="备注"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-textarea
          :rows="4"
          v-decorator="['remark', {rules: [{required: false, message: '备注不能为空'}]}]"/>
      </a-form-item>
    </a-form>
    <a-tabs type="card" default-active-key="1">
      <a-tab-pane key="1" tab="回收详情">
        <div class="table-operator">
          <a-button size="small" type="primary" @click="handleDetailSelect">
            <a-icon type="plus"/>
            添加
          </a-button>
          <a-button class="margin-left8" size="small" type="danger" @click="handleDel">
            <a-icon type="delete"/>
            删除
          </a-button>
        </div>
        <a-table
          bordered
          :data-source="data"
          :columns="columns"
          tableLayout="auto"
          rowKey="id"
          :row-selection="rowSelection">

        </a-table>
      </a-tab-pane>
    </a-tabs>
    <detail-base-form ref="detailBaseForm" @selected="handleDetailSelected"/>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>

  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addSparePickForm, updateSparePickForm } from '@/api/store/sparerecoveryform'
import DetailBaseForm from './DetailBaseForm'
import { queryUser } from '@/api/upms/user'

export default {
  name: 'BaseSpareRecoveryForm',
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map
      typeMap: {},
      statusMap: {},
      userList: [],
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '备件名称',
          dataIndex: 'spareId',
          customRender: (text, record, index) => {
            return record.spareName
          }
        },

      ],
      data: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      },
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      }
    }
  },
  components: {
    DetailBaseForm
  },
  props: {
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SPARE_RECOVERY_FORM_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SPARE_RECOVERY_FORM_STATUS)
    this.getUsers()
  },
  methods: {
    getUsers () {
      queryUser({ status: 1 }).then(res => {
        this.userList = res.data
      })
    },
    base (record) {
      this.visible = true
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        return
      }
      this.modalTitle = '编辑'
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'pickUserId',
          'pickUserName',
          'pickNo',
          'type',
          'repairId',
          'reason',
          'remark',
          'status'
        ])))
      })
      this.data = record.detailList
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.data.length === 0) {
          this.$message.error('请添加回收详情')
          this.confirmLoading = false
          return
        }
        values.detailList = this.data
        // 日期处理
        if (this.BaseTool.String.isBlank(values.id)) {
          addSparePickForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateSparePickForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    },

    handleDetailSelect () {
      this.$refs.detailBaseForm.base()
    },
    handleDetailSelected (record) {
      const { data } = this
      data.push(record)
    },
    handleDel () {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
    }

  }
}
</script>
